<template>
  <el-dialog
    v-model="dialogVisible"
    title="文章详情"
    width="90%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <div v-loading="loading" class="article-detail">
      <template v-if="article">
        <!-- 文章基本信息 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="title">基本信息</span>
              <div class="actions">
                <el-button
                  v-if="article.status === ArticleStatus.PENDING"
                  type="success"
                  size="small"
                  @click="handleAudit"
                >
                  审核
                </el-button>
                <el-button type="primary" size="small" @click="handleRefresh">
                  刷新
                </el-button>
              </div>
            </div>
          </template>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="文章ID">
                  {{ article.id }}
                </el-descriptions-item>
                <el-descriptions-item label="标题">
                  <span class="article-title">{{ article.title }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="作者">
                  <div class="author-info">
                    <el-avatar
                      v-if="article.authorAvatar"
                      :src="article.authorAvatar"
                      :size="24"
                    />
                    <span>{{ article.authorNickName }}</span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="分类">
                  <el-tag type="primary" style="color: #409eff">{{
                    article.categoryName
                  }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag
                    :type="
                      ArticleManagementUtils.getStatusTagType(
                        article.status
                      ) as any
                    "
                  >
                    {{ ArticleManagementUtils.getStatusText(article.status) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="标签">
                  <div class="tags">
                    <!-- 新版标签显示（优先使用） -->
                    <template
                      v-if="
                        article.articleTags && article.articleTags.length > 0
                      "
                    >
                      <el-tag
                        v-for="tag in article.articleTags"
                        :key="tag.id"
                        size="small"
                        :style="{
                          marginRight: '8px',
                          backgroundColor: tag.color,
                          color: '#ffffff',
                          border: `1px solid ${tag.color}`
                        }"
                      >
                        {{ tag.name }}
                      </el-tag>
                    </template>
                    <!-- 兼容旧版标签显示 -->
                    <template v-else-if="article.tags">
                      <el-tag
                        v-for="tag in parseOldTags(article.tags)"
                        :key="tag"
                        size="small"
                        type="info"
                        style="margin-right: 8px"
                      >
                        {{ tag }}
                      </el-tag>
                    </template>
                    <!-- 无标签时的显示 -->
                    <span v-else class="no-tags">暂无标签</span>
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="浏览量">
                  {{ ArticleManagementUtils.formatNumber(article.viewCount) }}
                </el-descriptions-item>
                <el-descriptions-item label="点赞数">
                  {{ ArticleManagementUtils.formatNumber(article.likeCount) }}
                </el-descriptions-item>
                <el-descriptions-item label="评论数">
                  {{
                    ArticleManagementUtils.formatNumber(article.commentCount)
                  }}
                </el-descriptions-item>
                <el-descriptions-item label="收藏数">
                  {{
                    ArticleManagementUtils.formatNumber(article.collectCount)
                  }}
                </el-descriptions-item>
                <el-descriptions-item label="字数">
                  {{ ArticleManagementUtils.formatNumber(article.wordCount) }}
                </el-descriptions-item>
                <el-descriptions-item label="阅读时长">
                  {{ article.readingTime }} 分钟
                </el-descriptions-item>
                <el-descriptions-item label="发布时间">
                  {{ article.publishTime || "-" }}
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">
                  {{ article.createTime }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>

          <!-- 文章摘要 -->
          <div class="summary-section">
            <h4>文章摘要</h4>
            <div class="summary-content">
              {{ article.summary }}
            </div>
          </div>

          <!-- 审核信息 -->
          <div
            v-if="
              article.auditRemark ||
              article.auditUserName ||
              article.auditReason
            "
            class="audit-section"
          >
            <h4>审核信息</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item v-if="article.auditUserName" label="审核人">
                {{ article.auditUserName }}
              </el-descriptions-item>
              <el-descriptions-item v-if="article.auditTime" label="审核时间">
                {{ article.auditTime }}
              </el-descriptions-item>
              <el-descriptions-item
                v-if="article.auditRemark"
                label="审核备注"
                :span="2"
              >
                {{ article.auditRemark }}
              </el-descriptions-item>
              <el-descriptions-item
                v-if="article.auditReason"
                label="审核原因"
                :span="2"
              >
                {{ article.auditReason }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>

        <!-- 文章内容 -->
        <el-card class="content-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="title">文章内容</span>
              <div class="content-tabs">
                <el-radio-group v-model="contentMode" size="small">
                  <el-radio-button value="preview">预览</el-radio-button>
                  <el-radio-button value="markdown">Markdown</el-radio-button>
                  <el-radio-button value="html">HTML</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>

          <div class="content-container">
            <!-- Markdown预览 -->
            <div v-if="contentMode === 'preview'" class="preview-content">
              <div
                v-if="!article.content && !article.htmlContent"
                class="empty-content"
              >
                <el-empty description="暂无内容" />
              </div>
              <MarkdownPreview
                v-else
                :content="article.content || ''"
                :html-content="article.htmlContent || ''"
              />
            </div>

            <!-- Markdown源码 -->
            <div
              v-else-if="contentMode === 'markdown'"
              class="markdown-content"
            >
              <el-input
                :model-value="article.content"
                type="textarea"
                :rows="20"
                readonly
                resize="none"
              />
            </div>

            <!-- HTML源码 -->
            <div v-else-if="contentMode === 'html'" class="html-content">
              <el-input
                :model-value="article.htmlContent"
                type="textarea"
                :rows="20"
                readonly
                resize="none"
              />
            </div>
          </div>
        </el-card>

        <!-- 内容特征 -->
        <el-card class="features-card" shadow="never">
          <template #header>
            <span class="title">内容特征</span>
          </template>

          <div class="features-grid">
            <div class="feature-item">
              <IconifyIconOnline
                :icon="article.hasCodeBlock ? 'ep:check' : 'ep:close'"
                :class="{ active: article.hasCodeBlock }"
              />
              <span>代码块</span>
            </div>
            <div class="feature-item">
              <IconifyIconOnline
                :icon="article.hasImage ? 'ep:check' : 'ep:close'"
                :class="{ active: article.hasImage }"
              />
              <span>图片</span>
            </div>
            <div class="feature-item">
              <IconifyIconOnline
                :icon="article.hasTable ? 'ep:check' : 'ep:close'"
                :class="{ active: article.hasTable }"
              />
              <span>表格</span>
            </div>
            <div class="feature-item">
              <IconifyIconOnline
                :icon="article.hasMath ? 'ep:check' : 'ep:close'"
                :class="{ active: article.hasMath }"
              />
              <span>数学公式</span>
            </div>
            <div class="feature-item">
              <IconifyIconOnline
                :icon="article.isTop === 1 ? 'ep:check' : 'ep:close'"
                :class="{ active: article.isTop === 1 }"
              />
              <span>置顶</span>
            </div>
            <div class="feature-item">
              <IconifyIconOnline
                :icon="article.isOriginal === 1 ? 'ep:check' : 'ep:close'"
                :class="{ active: article.isOriginal === 1 }"
              />
              <span>原创</span>
            </div>
          </div>
        </el-card>
      </template>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>

    <!-- 审核对话框 -->
    <ArticleAuditDialog
      v-model:visible="auditDialogVisible"
      :article="article"
      @refresh="handleRefresh"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import {
  getArticleDetailApi,
  type ArticleDetail,
  ArticleStatus,
  ArticleManagementUtils
} from "@/api/article-management";
import MarkdownPreview from "./MarkdownPreview.vue";
import ArticleAuditDialog from "./ArticleAuditDialog.vue";

defineOptions({
  name: "ArticleDetailDialog"
});

// Props
interface Props {
  visible: boolean;
  articleId: number | null;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  refresh: [];
}>();

// 响应式数据
const loading = ref(false);
const article = ref<ArticleDetail | null>(null);
const contentMode = ref<"preview" | "markdown" | "html">("preview");
const auditDialogVisible = ref(false);

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

// 解析旧版标签字符串
const parseOldTags = (tagsStr: string): string[] => {
  if (!tagsStr) return [];
  return tagsStr
    .split(",")
    .map(tag => tag.trim())
    .filter(tag => tag.length > 0);
};

// 监听文章ID变化
watch(
  () => props.articleId,
  newId => {
    if (newId && props.visible) {
      loadArticleDetail(newId);
    }
  },
  { immediate: true }
);

// 监听对话框显示状态
watch(
  () => props.visible,
  visible => {
    if (visible && props.articleId) {
      loadArticleDetail(props.articleId);
    } else if (!visible) {
      article.value = null;
      contentMode.value = "preview";
    }
  }
);

// 加载文章详情
const loadArticleDetail = async (articleId: number) => {
  try {
    loading.value = true;
    console.log("请求文章详情，ID:", articleId);
    const response = await getArticleDetailApi(articleId);
    console.log("完整响应:", response);
    console.log("响应数据:", response.data);

    // 处理API响应
    if (response.code === 200 && response.data) {
      article.value = response.data;
      console.log("文章详情设置成功:", {
        id: article.value.id,
        title: article.value.title,
        hasContent: !!article.value.content,
        contentLength: article.value.content?.length || 0,
        hasHtmlContent: !!article.value.htmlContent,
        htmlContentLength: article.value.htmlContent?.length || 0,
        tags: article.value.tags,
        articleTags: article.value.articleTags,
        tagCount: article.value.tagCount
      });
    } else {
      console.warn("响应数据格式异常:", response);
      ElMessage.error("文章详情数据格式异常");
    }
  } catch (error) {
    console.error("加载文章详情失败:", error);
    ElMessage.error("加载文章详情失败");
  } finally {
    loading.value = false;
  }
};

// 刷新文章详情
const handleRefresh = () => {
  if (props.articleId) {
    loadArticleDetail(props.articleId);
  }
  emit("refresh");
};

// 审核文章
const handleAudit = () => {
  auditDialogVisible.value = true;
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
// 响应式设计
@media (width <= 768px) {
  .article-detail {
    .card-header {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;

      .actions {
        justify-content: center;
      }

      .content-tabs {
        display: flex;
        justify-content: center;
      }
    }

    .features-grid {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}

.article-detail {
  .info-card,
  .content-card,
  .features-card {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }

    .actions {
      display: flex;
      gap: 8px;
    }

    .content-tabs {
      .el-radio-group {
        :deep(.el-radio-button__inner) {
          padding: 8px 16px;
        }
      }
    }
  }

  .article-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .author-info {
    display: flex;
    gap: 8px;
    align-items: center;
  }

  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .no-tags {
      font-size: 12px;
      font-style: italic;
      color: #909399;
    }
  }

  .summary-section,
  .audit-section {
    margin-top: 20px;

    h4 {
      margin: 0 0 12px;
      font-size: 14px;
      font-weight: 600;
      color: #606266;
    }

    .summary-content {
      padding: 12px;
      line-height: 1.6;
      color: #606266;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }

  .content-container {
    min-height: 400px;

    .preview-content {
      :deep(.markdown-body) {
        padding: 0;
      }

      .empty-content {
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 300px;
        background-color: #fafafa;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
      }
    }

    .markdown-content,
    .html-content {
      :deep(.el-textarea__inner) {
        font-family: Monaco, Menlo, "Ubuntu Mono", monospace;
        font-size: 13px;
        line-height: 1.5;
      }
    }
  }

  .features-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 16px;

    .feature-item {
      display: flex;
      gap: 8px;
      align-items: center;
      padding: 12px;
      background-color: #f5f7fa;
      border-radius: 6px;
      transition: all 0.3s ease;

      .iconify {
        font-size: 18px;
        color: #909399;

        &.active {
          color: #67c23a;
        }
      }

      span {
        font-size: 14px;
        color: #606266;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
